package com.easy.clickhouse;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.yandex.clickhouse.BalancedClickhouseDataSource;
import ru.yandex.clickhouse.settings.ClickHouseProperties;

/**
 * 
 * @author jetlag
 *
 */
@Configuration
@ConditionalOnClass({BalancedClickhouseDataSource.class})
public class ClickHouseAutoConfig {

    private CKProperties ckProperties;

    public ClickHouseAutoConfig(CKProperties ckProperties) {
        this.ckProperties = ckProperties;
    }

    @Bean
    public BalancedClickhouseDataSource clickHouseDataSource() {
        ClickHouseCluster clickHouseCluster = ckProperties.getCluster();
        String clusterAddress = clickHouseCluster.getClusterAddress();
        ClickHouseProperties properties = clickHouseCluster.getClusterProperties();
        BalancedClickhouseDataSource dataSource = new BalancedClickhouseDataSource(clusterAddress, properties);
        dataSource.scheduleActualization(ckProperties.getCheckInterval(), ckProperties.getTimeUnit());
        return dataSource;
    }

    @Bean
    public ClickHouseTemplate clickHouseTemplate(){
        return new ClickHouseTemplate();
    }

}
